//
// Created by WenDaoJiang on 2017/6/19.
// Copyright (c) 2017 文道江. All rights reserved.
//

#import <MediaPlayer/MediaPlayer.h>
#import "CallVideoViewController.h"
#import "HybridBridge.h"
#import "LZRelayoutButton.h"
#import "ImageButton.h"
#import "ChatVideoController.h"
#import "PlayVibrate.h"
#import "AlertView.h"
#import "ServerApi.h"

@implementation CallVideoViewController {
    BOOL _isCall; // 是否是发起呼叫端
    NSInteger myUid;
    NSTimer *_timer;
}


- (void)viewDidLoad {
    [super viewDidLoad];

    _isCall = (_callInfo!=nil && _callInfo[@"isCall"] == nil) ? NO : [_callInfo[@"isCall"] boolValue];

    NSDictionary *info = [KVStorage getJsonValue:@"agora_signal_login_info"];
    myUid = info != nil ? [info[@"uid"] integerValue] : 0;

    // 禁止自动休眠
    [UIApplication sharedApplication].idleTimerDisabled = YES;

    // 注册挂断事件监听
    [[HybridEventBus defaultEventBus] addObserver:self selector:@selector(onVideoEndCall:) name:@"agora_signal_on_end_call" object:nil];
    [[HybridEventBus defaultEventBus] addObserver:self selector:@selector(onInVideoChat:) name:@"agora_signal_in_video_chat" object:nil];

    CGFloat height = self.view.frame.size.height;
    CGFloat width = self.view.frame.size.width;
    
    // 设置背景
    UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"video_call_bg.png"]];
    imgView.frame = self.view.bounds;
    imgView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [self.view insertSubview:imgView atIndex:0];

    UILabel *topMsg = [self makeLabel:_isCall ? @"正在申请视频面试" : @"视频面试申请，是否接通？" fontSize:24 Top:_isCall ? 150 : 50 Width:width];
    [self.view addSubview:topMsg];

    NSDictionary *ex = _callInfo[@"ext_data"];

    NSLog(@"_callInfo %@", _callInfo);
    NSLog(@"_callInfo exData %@", ex);

    if(!_isCall){

        // 头像
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
        imageView.center = CGPointMake(self.view.center.x, 150);
        [imageView setImageWithURL:[NSURL URLWithString:ex[@"fromUserAvatar"]] placeholderImage:[UIImage imageNamed:@"no_avatar.png"]];
        imageView.layer.cornerRadius = 50;
        imageView.layer.masksToBounds = YES;
        [self.view addSubview:imageView];

        // 姓名与性别
        UILabel *fromUserName = [self makeLabel:ex[@"fromUserName"] fontSize:20 Top:220 Width:200];
        [self.view addSubview:fromUserName];
        UIImageView *sexImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[@"M" isEqualToString:ex[@"fromUserSex"]] ? @"video_man.png" : @"video_woman.png"]];
        sexImg.frame = CGRectMake(0, 0, 16, 12);
        sexImg.center = CGPointMake(fromUserName.center.x + (fromUserName.bounds.size.width / 2) + 10, fromUserName.center.y);
        [self.view addSubview:sexImg];

        // 年龄
        UILabel *fromAge = [self makeLabel:[NSString stringWithFormat:@"%i岁", [ex[@"fromUserAge"] integerValue]] fontSize:16 Top:250 Width:200];
        [self.view addSubview:fromAge];
    }


    CGFloat jobTop = self.view.bounds.size.height / 2;

    [self.view addSubview:[self makeLabel:@"申请面试岗位" fontSize:14 Top:jobTop Width:200]];

    UIView *jobRect = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width - 40, 100)];
    jobRect.center = CGPointMake(self.view.center.x, jobTop + 70);
    jobRect.layer.backgroundColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:.1].CGColor;
    jobRect.layer.cornerRadius = 4;

    UILabel *jobName = [self makeLabel:ex[@"jobName"] fontSize:20 Top:0 Width:jobRect.frame.size.width - 40];
    jobName.center = CGPointMake(jobRect.frame.size.width / 2, 40);
    jobName.numberOfLines = 2;
    [jobRect addSubview:jobName];

    UILabel *jobWorkTime = [self makeLabel:[NSString stringWithFormat:@"上班时间：%@", ex[@"jobWorkTime"]] fontSize:14 Top:0 Width:jobRect.frame.size.width - 40];
    jobWorkTime.center = CGPointMake(jobRect.frame.size.width / 2, 70);
    jobWorkTime.textColor = UIColor.grayColor;
    [jobRect addSubview:jobWorkTime];

    [self.view addSubview:jobRect];

    if(!_isCall){
        if (ex[@"alreadyHiredJobName"] != nil && ![@"" isEqualToString:ex[@"alreadyHiredJobName"]]) {

            UILabel *alreadyHiredJobName = [self makeLabel:[NSString stringWithFormat:@"您曾经在\"%@\"中已面试并录用过TA，您如果认为他合适，可以选择免面试直接通过。", ex[@"alreadyHiredJobName"]] fontSize:14 Top:0 Width:jobRect.frame.size.width];
            alreadyHiredJobName.textColor = UIColor.orangeColor;
            alreadyHiredJobName.center = CGPointMake(width / 2, jobRect.center.y + jobRect.bounds.size.height / 2 + 40);
            alreadyHiredJobName.numberOfLines = 0;

            [self.view addSubview:alreadyHiredJobName];

            ImageButton *passButton = [ImageButton buttonWithType:UIButtonTypeCustom];
            passButton.center = CGPointMake(width / 2, height - 80);
            [passButton setTitle:@"直接通过" forState:UIControlStateNormal];
            [passButton setImage:[UIImage imageNamed:@"video_end2.png"] forState:UIControlStateNormal];

            [passButton addTarget:self action:@selector(passClick:) forControlEvents:UIControlEventTouchUpInside];

            [self.view addSubview:passButton];

        }

        // 接通
        ImageButton *acceptCallButton = [ImageButton buttonWithType:UIButtonTypeCustom];
        acceptCallButton.center = CGPointMake(width - 60, height - 80);
        [acceptCallButton setTitle:@"接通" forState:UIControlStateNormal];
        [acceptCallButton setImage:[UIImage imageNamed:@"video_call.png"] forState:UIControlStateNormal];

        [acceptCallButton addTarget:self action:@selector(acceptCallClick:) forControlEvents:UIControlEventTouchUpInside];

        [self.view addSubview:acceptCallButton];
    }

    ImageButton *endCallButton = [ImageButton buttonWithType:UIButtonTypeCustom];
    endCallButton.center = CGPointMake(_isCall ? width / 2 : 60, height - 80);
    [endCallButton setTitle: _isCall ? @"取消" : @"挂断" forState:UIControlStateNormal];
    [endCallButton setImage:[UIImage imageNamed:@"video_end.png"] forState:UIControlStateNormal];

    [endCallButton addTarget:self action:@selector(endCallClick:) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:endCallButton];


    if(!PlayVibrate.shareInstance.playing){
        if(_isCall){
            [PlayVibrate.shareInstance playSound];
        }else{
            [[PlayVibrate shareInstance] playVibrate];
        }
    }
    NSInteger timeout = [_callInfo[@"timeout"] integerValue];
    if(timeout > 0){
        _timer = [NSTimer scheduledTimerWithTimeInterval:timeout  target:self selector:@selector(handlerTimeout) userInfo:nil repeats:NO];
    }
}

- (UILabel *)makeLabel:(NSString *)text fontSize:(NSInteger)fontSize Top:(CGFloat)top Width:(CGFloat)width {

    UIFont *font = [UIFont systemFontOfSize:fontSize];

    CGSize strSize = CGSizeMake(width, MAXFLOAT);
    CGSize labelSize = [text boundingRectWithSize:strSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{
            NSFontAttributeName: font
    }                                     context:nil].size;

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, labelSize.width, labelSize.height)];

    label.text = text;
    label.textColor = UIColor.whiteColor;
    label.textAlignment = NSTextAlignmentCenter;
    label.font = font;
    label.center = CGPointMake(self.view.center.x, top);

    return label;
}

- (void)openVideoChat:(NSDictionary *)userInfo {
    dispatch_async(dispatch_get_main_queue(), ^{
        ChatVideoController *chatVideoController = [[ChatVideoController alloc] init];
        chatVideoController.appID = _appID;
        chatVideoController.channelName = [NSString stringWithFormat:@"video_channel_%@", userInfo[@"sid"]];
        chatVideoController.callInfo = _callInfo;

        if (self.navigationController != nil) {
            NSMutableArray *viewController = [NSMutableArray arrayWithArray:[self.navigationController viewControllers]];
            [viewController removeLastObject];
            [viewController addObject:chatVideoController];
            [self.navigationController setViewControllers:viewController];
        } else {
            [self presentViewController:chatVideoController animated:NO completion:^{
                [self dismissViewControllerAnimated:NO completion:nil];
            }];
        }
    });
}

// 收到结束命令
- (void)onVideoEndCall:(NSNotification *)notification {
    [self dismissSelf];
}

// 收到加入聊天指令
- (void)onInVideoChat:(NSNotification *)notification {
    [self openVideoChat:notification.userInfo];
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

// 拒绝/取消
- (void)endCallClick:(UIButton *)sender {
    [self emitEndCall:_isCall ? @"cancel" : @"reject" data:_callInfo[@"ext_data"]];
    [self dismissSelf];
}

// 接通
- (void)acceptCallClick:(UIButton *)sender {
    [[HybridEventBus defaultEventBus] postData:@{
            @"sid": _callInfo[@"sid"]
    } Tag:@"signal_emit_accept_call"];
    [self openVideoChat:_callInfo];
}

// 直接通过
- (void)passClick:(UIButton *)sender {

    [[PlayVibrate shareInstance] stopPlayVibrate];

    if(_callInfo == nil || _callInfo[@"ext_data"] == nil){
        [AlertView alertWithTitle:@"操作失败" Message:@"数据有误，请稍后再试" Callback:^(NSInteger buttonIndex) {
            [[HybridEventBus defaultEventBus] postData:@{
                    @"sid": _callInfo[@"sid"],
                    @"typeName": @"reject"
            } Tag:@"signal_emit_end_call"];
            [self dismissSelf];
        }];
        return;
    }

    NSDictionary *body = @{
            @"userWorkerId": _callInfo[@"from_uid"],
            @"interviewBeginTime": _callInfo[@"created_at"],
            @"interviewEndTime": _callInfo[@"created_at"],
            @"interviewStatus": @"P",
            @"orderId": _callInfo[@"ext_data"][@"jobId"]
    };

    [AlertView confirmWithTitle:@"确定通过吗？" Message:@"通过即代表同意对方按照订单要求前来上班。\n确定后将自动挂断视频，结束面试" CallBack:^(NSInteger buttonIndex) {
        if (buttonIndex == 1) {

            [[HybridEventBus defaultEventBus] postData:@{
                    @"sid": _callInfo[@"sid"],
                    @"typeName": @"directPass"
            } Tag:@"signal_emit_end_call"];

            [[ServerApi new] callProgresWithView:self.view act:@"/B/Order/Do/Interview" body:body completionHandler:^(NSDictionary *data, NSError *error) {

                if(error){
                    [AlertView alertWithTitle:@"" Message:error.domain Callback:^(NSInteger b) {
                        [self dismissSelf];
                    }];
                }else{
                    if (data != nil && data[@"interviewContent"] != nil) {
                        [AlertView alertWithTitle:@"" Message:[NSString stringWithFormat:@"%@", data[@"interviewContent"]] Callback:^(NSInteger b) {
                            [self dismissSelf];
                        }];
                    }else{
                        [self dismissSelf];
                    }
                }

                NSLog(@"ajax result data: %@", data);
                if (error) NSLog(@"ajax result data: err: %@", error);
            }];
        }
    }];

}

// 超时未接通
- (void)handlerTimeout{
    if(_timer != nil){
        [_timer invalidate];
        _timer = nil;
    }
    [self emitEndCall:@"timeout" data:_callInfo[@"ext_data"]];
    [self dismissSelf];
}

// ------
- (void)dismissSelf {
    if (self.navigationController != nil) {
        [self.navigationController popViewControllerAnimated:NO];
    } else {
        [self dismissViewControllerAnimated:NO completion:nil];
    }
}

- (void)emitEndCall:(NSString *)typeName data:(id)data {
    if(_callInfo && _callInfo[@"sid"] != nil){
        [[HybridEventBus defaultEventBus] postData:@{
                @"sid": _callInfo[@"sid"],
                @"typeName": typeName,
                @"data": data == nil ? @{} : data,
                @"fromUid": @(myUid)
        } Tag:@"signal_emit_end_call"];
    }
}

- (void)viewDidDisappear:(BOOL)animated {
    if(_isCall){
        [[PlayVibrate shareInstance] stopSound];
    }else{
        [[PlayVibrate shareInstance] stopPlayVibrate];
    }
    if(_timer != nil){
        [_timer invalidate];
        _timer = nil;
    }

    [UIApplication sharedApplication].idleTimerDisabled = NO;

    [HybridEventBus.defaultEventBus removeObserver:self name:@"agora_signal_on_end_call" object:nil];
    [HybridEventBus.defaultEventBus removeObserver:self name:@"agora_signal_in_video_chat" object:nil];
}

@end